import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/models/class/ClassDetails.dart';
import 'package:ichinesereader/models/teacher/TeacherDto.dart';
import 'package:ichinesereader/pages/schooladmin/adminClassEditor.dart';
import 'package:ichinesereader/pages/schooladmin/studentsManagement.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:intl/intl.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/themes/buttonStyles.dart';

// ignore: must_be_immutable
class ClassDataGrids extends StatelessWidget {
  ClassDataGrids(this.isWebOrDesktop, this.classItems);

  List<ClassDetails> classItems;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();
  final SchoolAdminController _schoolAdminController = Get.find();
  AppButtonStyles _appButtonStyles = new AppButtonStyles();

  @override
  Widget build(BuildContext context) {
    Log.debug('build ClassDataGrids');
    return Container(
      margin: const EdgeInsets.fromLTRB(0.0, 33.0, 12.0, 33.0),
      child: Column(children: [
        Container(
          padding: EdgeInsets.all(12.0),
          decoration: BoxDecoration(
            color: Get.isDarkMode
                ? AppTheme.colors.darkTheme2
                : Colors.white.withOpacity(0.3),
            borderRadius: BorderRadius.circular(3.0),
          ),
          child: Row(
            children: [
              ElevatedButton(
                  style: _appButtonStyles.createButtonStyle(),
                  child: Text(
                    'Create'.tr,
                    style: TextStyle(
                        color: Get.isDarkMode ? Colors.black : Colors.white),
                  ),
                  onPressed: () {
                    _schoolAdminController.resetClassDetailsNew();
                    Get.to(() => AdminClassEditor());
                  }),
              SizedBox(width: 12),
              ElevatedButton(
                  style: _appButtonStyles.removeButtonStyle(),
                  child: Text(
                    'Remove'.tr,
                    style: TextStyle(
                        color: Get.isDarkMode ? Colors.black : Colors.white),
                  ),
                  onPressed: () {
                    if (this._dataGridController.selectedRows.length > 0) {
                      this._dataGridController.selectedRows.forEach((row) {
                        var cid = row
                            .getCells()
                            .where((element) => element.columnName == 'Id')
                            .first
                            .value;

                        var item = classItems
                            .where((element) => element.classId == cid)
                            .first;
                        if (item.students != null &&
                            item.students!.length > 0) {
                          Get.snackbar(
                              'Message'.tr,
                              'Class could not be DELETED when there are students in this class!'
                                  .tr,
                              backgroundColor: Theme.of(context).primaryColor,
                              colorText: Theme.of(context).primaryColorLight,
                              snackPosition: SnackPosition.BOTTOM);
                        } else {
                          _schoolAdminController
                              .removeClasss(item.classId.toString())
                              .then((statusMessage) {
                            if (statusMessage.status == 1000) {
                              Get.snackbar(
                                  'Message'.tr, 'Successfully deleted'.tr,
                                  backgroundColor:
                                      Theme.of(context).primaryColor,
                                  colorText:
                                      Theme.of(context).primaryColorLight,
                                  snackPosition: SnackPosition.BOTTOM);
                            } else {
                              Get.snackbar('Message'.tr,
                                  'Remove class not successful'.tr,
                                  backgroundColor:
                                      Theme.of(context).primaryColor,
                                  colorText:
                                      Theme.of(context).primaryColorLight,
                                  snackPosition: SnackPosition.BOTTOM);
                            }
                          });
                        }
                      });
                    }
                  }),
            ],
          ),
        ),
        SizedBox(height: 12),
        Expanded(child: _buildDataGrid()),
      ]),
    );
  }

  Container _buildDataGrid() {
    if (GetPlatform.isDesktop || GetPlatform.isWeb) isWebOrDesktop = true;

    return Container(
      padding: EdgeInsets.all(12.0),
      decoration: BoxDecoration(
        color: Get.isDarkMode
            ? AppTheme.colors.darkTheme2
            : Colors.white.withOpacity(0.3),
        borderRadius: BorderRadius.circular(3.0),
      ),
      child: Container(
        decoration: BoxDecoration(
          color: Get.isDarkMode ? AppTheme.colors.darkTheme2 : Colors.white,
          boxShadow: [
            BoxShadow(
              blurRadius: 6,
              spreadRadius: 3,
              color: Get.isDarkMode
                  ? Colors.transparent
                  : Colors.black.withOpacity(0.1),
              offset: Offset(1, 1),
            ),
          ],
        ),
        child: SfDataGrid(
          source: ClassDataGridSource(items: classItems),
          isScrollbarAlwaysShown: true,
          onQueryRowHeight: (row) {
            return row.rowIndex == 0 ? 50.0 : 49.0;
          },
          //设置表头高度
          showCheckboxColumn: true,
          checkboxColumnSettings: Get.isDarkMode
              ? DataGridCheckboxColumnSettings(
                  backgroundColor: Color(0xff0a0e21),
                )
              : DataGridCheckboxColumnSettings(
                  backgroundColor: Colors.blue[50]),
          allowSorting: true,
          allowTriStateSorting: true,
          //sortingGestureType: SortingGestureType.doubleTap,
          allowSwiping: true,
          allowFiltering: true,
          columnWidthMode: ColumnWidthMode.auto,
          columnWidthCalculationRange: ColumnWidthCalculationRange.allRows,
          selectionMode: SelectionMode.multiple,
          navigationMode: GridNavigationMode.row,
          controller: _dataGridController,
          endSwipeActionsBuilder:
              (BuildContext context, DataGridRow row, int rowIndex) {
            return GestureDetector(
                onTap: () {
                  var cid = row
                      .getCells()
                      .where((element) => element.columnName == 'Id')
                      .first
                      .value;
                  var item = classItems
                      .where((element) => element.classId == cid)
                      .first;
                  if (item.students != null && item.students!.length > 0) {
                    Get.snackbar(
                        'Message'.tr,
                        'Class could not be DELETED when there are students in this class!'
                            .tr,
                        backgroundColor: Theme.of(context).primaryColor,
                        colorText: Theme.of(context).primaryColorLight,
                        snackPosition: SnackPosition.BOTTOM);
                  } else {
                    _schoolAdminController
                        .removeClasss(item.classId.toString())
                        .then((statusMessage) {
                      if (statusMessage.status == 1000) {
                        Get.snackbar('Message'.tr, 'Successfully deleted'.tr,
                            backgroundColor: Theme.of(context).primaryColor,
                            colorText: Theme.of(context).primaryColorLight,
                            snackPosition: SnackPosition.BOTTOM);
                      } else {
                        Get.snackbar(
                            'Message'.tr, 'Remove class not successful'.tr,
                            backgroundColor: Theme.of(context).primaryColor,
                            colorText: Theme.of(context).primaryColorLight,
                            snackPosition: SnackPosition.BOTTOM);
                      }
                    });
                  }
                },
                child: Container(
                    color: Colors.redAccent,
                    child: Center(
                      child: Icon(Icons.delete),
                    )));
          },
          columns: <GridColumn>[
            GridColumn(
              width: 280,
              columnName: 'ClassName',
              label: buildDataGridColumnLabel('ClassName'),
            ),
            GridColumn(
              columnName: 'Teacher',
              width: 360,
              label: buildDataGridColumnLabel('Teacher(s)'),
            ),
            GridColumn(
              columnName: 'Students',
              allowFiltering: false,
              width: isWebOrDesktop ? 140 : 100,
              label: buildDataGridColumnLabel('Students'),
            ),
            GridColumn(
              columnName: 'Homework',
              allowFiltering: false,
              width: isWebOrDesktop ? 150 : 120,
              label: buildDataGridColumnLabel('Homework'),
            ),
            GridColumn(
              columnName: 'Details',
              allowFiltering: false,
              width: isWebOrDesktop ? 150 : 120,
              label: buildDataGridColumnLabel('Details'),
            ),
            GridColumn(
              columnName: 'CreatedDate',
              allowFiltering: false,
              width: isWebOrDesktop ? 170 : 130,
              label: buildDataGridColumnLabel('CreateDate'),
            ),
            GridColumn(
              columnName: 'Id',
              allowFiltering: false,
              visible: false,
              label: buildDataGridColumnLabel('Id'),
            ),
          ],
        ),
      ),
    );
  }
}

class ClassDataGridSource extends DataGridSource {
  ClassDataGridSource({required List<ClassDetails> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'ClassName', value: dataGridRow.className),
              DataGridCell<String>(
                  columnName: 'Teacher',
                  value: dataGridRow.teachers != null
                      ? json.encode(dataGridRow.teachers)
                      : null),
              DataGridCell<int>(
                  columnName: 'Students', value: dataGridRow.students?.length),
              DataGridCell<int>(
                  columnName: 'Homework', value: dataGridRow.numOfAssignment),
              DataGridCell<String>(columnName: 'Details', value: 'VIEW/MODIFY'),
              DataGridCell<int>(
                  columnName: 'CreatedDate', value: dataGridRow.createDate),
              DataGridCell<String>(
                  columnName: 'Id', value: dataGridRow.classId),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];
  final SchoolAdminController _schoolAdminController = Get.find();

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'CreatedDate') {
            if (dataGridCell.value > 0) {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    DateFormat('yyyy-MM-dd kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall,
                  ));
            } else {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    '',
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall,
                  ));
            }
          } else if (dataGridCell.columnName == 'Details') {
            return Container(
                alignment: Alignment.centerLeft,
                //width: 180,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: GestureDetector(
                  onTap: () {
                    String classId = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    if (_schoolAdminController.classItems
                        .where((element) => element.classId == classId)
                        .isNotEmpty) {
                      var tc = _schoolAdminController.classItems
                          .where((element) => element.classId == classId)
                          .first;
                      _schoolAdminController.setSchoolAdminCurrentClass(tc);
                      Get.to(() => AdminStudentsManagement(classId: classId));
                    }

                    //int studentsNum = row.getCells().where((element) => element.columnName == 'Students').first.value;
                    // if(studentsNum>0)
                    //   Get.to(() => AdminStudentsManagement(classId: classId));
                    // else
                    //   Get.to(() => AddStudentsToClassSchoolAdminPage(classId: classId));
                  },
                  child: Text(
                    dataGridCell.value.toString(),
                    style: Get.textTheme.titleLarge,
                    overflow: TextOverflow.ellipsis,
                  ),
                ));
          } else if (dataGridCell.columnName == 'ClassName') {
            return Container(
                alignment: Alignment.centerLeft,
                //width: 180,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: GestureDetector(
                  onTap: () {
                    String classId = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    Get.to(() => AdminClassEditor(classId: classId));
                  },
                  child: Text(
                    dataGridCell.value.toString(),
                    style: Get.textTheme.titleLarge,
                    overflow: TextOverflow.ellipsis,
                  ),
                ));
          } else if (dataGridCell.columnName == 'Teacher') {
            var tempstr = '';
            if (dataGridCell.value != '[]') {
              List<TeacherDto> teachers =
                  teacherDtoFromJson(dataGridCell.value);
              teachers.forEach((element) {
                tempstr = tempstr + element.userName.toString() + ',';
              });
              tempstr = tempstr.substring(0, tempstr.length - 1);
            }
            return Container(
                alignment: Alignment.centerLeft,
                //width: 180,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  tempstr,
                  softWrap: true,
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value.toString(),
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
